package com.cxl.controller;


import cn.hutool.jwt.JWT;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.cxl.ann.LogAnn;
import com.cxl.config.AjaxResult;
import com.cxl.entity.User;
import com.cxl.service.IUserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RestController;

import java.nio.charset.StandardCharsets;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author 崔学磊
 * @since 2022-03-16
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private IUserService iUserService;

    @Autowired
    private KafkaTemplate kafkaTemplate;

    @Autowired
    private RedisTemplate redisTemplate;

    //@Log,使用AOP拦截controller的所有方法
    @LogAnn(value = "login")
    @PostMapping(value = "/login")
    public AjaxResult login(@RequestBody User user) {
        if (StringUtils.isNoneBlank(user.getUsername()) && StringUtils.isNoneBlank(user.getPassword())) {
            //验证用户名或密码
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("username", user.getUsername());
            queryWrapper.eq("password", user.getPassword());
            User one = iUserService.getOne(queryWrapper);
            if (one != null) {
                String token = JWT.create()
                        .setPayload("username", one.getUsername())
                        .setPayload("password", one.getPassword())
                        .setKey("1".getBytes(StandardCharsets.UTF_8))
                        .sign();
                //登录成功后，通过kafka进行消息发送到日志服务
                kafkaTemplate.send("log", "add", JSON.toJSONString(one));
                redisTemplate.opsForValue().set(token, one);
                return AjaxResult.ok(token);
            }
            return AjaxResult.err(500, "用户名或密码错误");
        }
        return AjaxResult.err(500, "用户名密码不能为空");
    }
}
